<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="toggle" label-width="68px">
      <el-form-item label="歌单名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入您要查询的歌单名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建者" prop="username" label-width="120px">
        <el-input
          v-model="username"
          placeholder="请输入您要查询的创建者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="createTime" size="medium">
        <el-date-picker
          v-model="createTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <div class="right-toolbar">
        <el-tooltip class="item" effect="dark" :content="toggle?'隐藏搜索':'显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="toggle=!toggle"/>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getList"/>
        </el-tooltip>
      </div>
    </el-row>

    <el-table :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="id" width="80" sortable/>
      <el-table-column label="歌单名" align="center" prop="name">
        <template slot-scope="scope">
          <el-link type="primary" @click="goto(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="user.username"/>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="创建日期" align="center" prop="createTime" sortable/>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <img :src="base_api+scope.row.image" :width="50" :height="50" alt="暂无图片"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryParams.pageSize"
      layout="->,total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="歌单名" prop="name">
          <el-input v-model="form.name" placeholder="请输入歌单名"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="uploadApi"
            :show-file-list="false"
            :on-success="(res,file,fileList)=>handleUploadSuccess(res,file,fileList,'AVATAR')"
            :before-upload="(file)=>handleBeforeUpload(file,'AVATAR')"
            :on-remove="(file,fileList)=>handleRemove(file,fileList,'AVATAR')">
            <img v-if="form.image" :src="base_api+form.image" class="img"/>
            <i v-else class="el-icon-plus img-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addMenu, deleteMenus, getMenuList, updateMenu} from "@/api/menu";
import {getUserList} from "@/api/appUser";

const BASE_API = process.env.VUE_APP_BASE_API
const UPLOAD_API = BASE_API + 'music/file/upload'
export default {
  name: "User",
  data() {
    return {
      base_api: BASE_API,
      uploadApi: UPLOAD_API,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        userId: null,
        startTime: null,
        endTime: null
      },
      createTime: null,
      username: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{required: true, message: '请输入歌单名', trigger: 'blur'}],
      },
      toggle: true
    }
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      let username = this.username
      if (this.createTime !== null) {
        this.queryParams.startTime = this.createTime[0]
        this.queryParams.endTime = this.createTime[1]
      }
      if (username) {
        await getUserList({username: this.username}).then(res => {
          if (res.data.list.length !== 0)
            this.queryParams.userId = res.data.list[0].id
          else
            this.queryParams.userId = 0
        }).catch(err => console.log(err))
      }
      getMenuList(this.queryParams).then(res => {
        this.userList = res.data.list
        this.total = res.data.count
        this.queryParams = {
          userId: null,
          startTime: null,
          endTime: null
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        name: null,
        description: null,
        image: null
      };
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.$refs.form.clearValidate()
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        username: null,
        userId: null,
        startTime: null,
        endTime: null
      }
      this.username = null
      this.createTime = null
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ids = row.id || this.ids
      getMenuList({
        id: ids.toString()
      }).then(response => {
        this.form = response.data.list[0];
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMenu(this.form).then(response => {
              this.$message.success("修改成功")
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            this.form.userId = 1
            addMenu(this.form).then(response => {
              this.$message.success("新增成功")
              this.open = false;
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return deleteMenus(ids);
      }).then(() => {
        this.getList();
        this.$message("删除成功");
      }).catch(() => {
      });
    },
    // 文件上传操作
    handleUploadSuccess(res, file, fileList, type) {
      if (res.code !== 200) this.$message.error((res.msg))
      else {
        if (type === 'AVATAR') {
          this.form.image = res.data
        }
      }
    },
    handleBeforeUpload(file, type) {
      console.log(file)
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      let isImage
      if (type === 'AVATAR') {
        isImage = file.type.startsWith('image')
        if (!isImage) {
          this.$message.error('上传图片格式!')
        }
      }
      return isImage && isLt10M
    },
    handleRemove(file, fileList, type) {
      if (type === 'AVATAR') {
        this.form.image = ''
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
      console.log(`当前页: ${val}`);
    },
    /** 跳转详情页 */
    goto(row) {
      this.$router.push("menu/detail/" + row.id)
    }
  }
}
</script>
<style scoped lang="scss">

$size: 150px;
$color: #DCDFE6;

.avatar-uploader {
  width: $size;
  height: $size;
  border: 1px dashed $color;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  font-size: 28px;
  color: rgba(96, 98, 102);
}

.img {
  margin-top: 10px;
  width: 100%;
  height: 100%;
  border-radius: 5px;
}

.right-toolbar {
  float: right;
}

</style>
